package com.girlbook.controllers;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;

@Path("file")
public class FileController
{
	/**
	 * 文件上传页面
	 * @return
	 */
	@Get("/view")
	public String view()
	{
		return "fileupload" ;
	}	
	

	/**
	 * 文件上传操作
	 * @param inv
	 * @throws Exception
	 */
	@Get("upload")
	public String upload() throws Exception 
	{
		return "@call POST with multipart form data";
	}
	
	/**
	 * 文件上传操作
	 * @param inv
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@Post("upload")
	public String upload(Invocation inv, MultipartFile[] files) throws Exception 
	{
		HttpServletRequest request = inv.getRequest();
		HttpServletResponse response = inv.getResponse();
        if (!ServletFileUpload.isMultipartContent(request))
        {
            throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");
        }

        ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
        response.setContentType("text/plain");
        
        List<FileItem> items = uploadHandler.parseRequest(request);
        for (FileItem item : items)
        {
            if (!item.isFormField())
            {
                File file = File.createTempFile(item.getName(), "");
                item.write(file);
                return "@{\"name\":\"" + item.getName() + "\",\"type\":\"" + item.getContentType() + "\",\"size\":\"" + item.getSize() + "\"}";
            }
        }

        return "@";
	}

}
